package com.atguigu.srb.sms.controller;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.utils.R;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.common.utils.ResponseEnum;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.MsmApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
//@CrossOrigin    //跨域
@Api(tags = "短信服务")
@RestController
@RequestMapping("/api/sms")
public class MsmApiController {

    @Resource
    private CoreUserInfoClient userInfoClient;

    @Resource
    private MsmApiService msmApiService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;
 
    //发送手机验证码
    @ApiOperation("获取验证码")
    @GetMapping("send/{phone}")
    public R sendCode(@PathVariable("phone") String phone) {

        //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
        Assert.notEmpty(phone, ResponseEnum.MOBILE_NULL_ERROR);
        //MOBILE_ERROR(-203, "手机号不正确"),
        Assert.isTrue(RegexValidateUtils.checkCellphone(phone), ResponseEnum.MOBILE_ERROR);

        //手机号是否已经注册
        boolean result = userInfoClient.checkMobile(phone);
        Assert.isTrue(result==false,ResponseEnum.MOBILE_EXIST_ERROR);

        //如果从redis获取不到，
        // 生成验证码，生成6位验证码
        String code = RandomUtils.getSixBitRandom();
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = msmApiService.send(phone,code);
        //生成验证码放到redis里面，设置有效时间
        if(isSend) {
            // key 手机号  value 验证码
            redisTemplate.opsForValue().set("srb:sms:code:"+phone,code,2, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error("发送短信失败");
        }
    }
}